<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<script>
require([
    'jquery',
    "uiRegistry",
    'Magento_Ui/js/modal/alert',
    'prototype'
], function(jQuery, registry, alert){

//<![CDATA[
var couponTypeSpecific = '<?php /* @escapeNotVerified */ echo \Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC ?>',
    couponTypeAuto = '<?php /* @escapeNotVerified */ echo \Magento\SalesRule\Model\Rule::COUPON_TYPE_AUTO ?>',
    tmpButtonsActionsStorage = [];

function disableEnableCouponsTabContent(disable) {
    var containerId = 'promo_catalog_edit_tabs_coupons_section_content',
        couponCode = $('rule_coupon_code');

    if($(containerId)){
        var dataFields = $(containerId).select('input', 'select', 'textarea', 'button');
        for(var i = 0; i < dataFields.length; i++) {
            disable ? dataFields[i].disable().addClassName('disabled')
                : dataFields[i].enable().removeClassName('disabled');
        }
    }

    couponCode.disabled = !disable;
}

function handleCouponsTabContentActivity() {
    jQuery('#couponCodesGrid').addClass('ignore-validate');
    var disable = !($('rule_coupon_type').value === couponTypeAuto || $('rule_use_auto_generation').checked);
    disableEnableCouponsTabContent(disable);
}

function handleCouponTypeChange() {
    $('rule_coupon_type').observe('change', function() {
        var disable = this.value !== couponTypeAuto;
        if (disable) {
            disable = !(this.value === couponTypeSpecific && $('rule_use_auto_generation').checked);
        }
        disableEnableCouponsTabContent(disable);
    });
}

function refreshCouponCodesGrid(grid, gridMassAction, transport) {
    grid.reload();
    gridMassAction.unselectAll();
}

function generateCouponCodes(idPrefix, generateUrl, grid) {
    $(idPrefix + 'information_fieldset').removeClassName('ignore-validate');
    var validationResult = $(idPrefix + 'information_fieldset').select('input',
            'select', 'textarea').collect( function(elm) {
        return jQuery.validator.validateElement(elm);
    }).all();
    $(idPrefix + 'information_fieldset').addClassName('ignore-validate');

    if (!validationResult) {
        return;
    }
    var elements = $(idPrefix + 'information_fieldset').select('input', 'select', 'textarea');

    elements = elements.concat(
        $$('#rule_uses_per_coupon'),
        $$('#rule_uses_per_customer'),
        $$('#rule_to_date')
    );

    var params = Form.serializeElements(elements, true);
    params.form_key = FORM_KEY;
    if ($$('#'+idPrefix + 'information_fieldset .messages')) {
        $$('#'+idPrefix + 'information_fieldset .messages')[0].update();
    }
    if ($('messages')) {
        $('messages').update();
    }
    var couponCodesGrid = eval(grid);
    new Ajax.Request(generateUrl, {
        parameters :params,
        method :'post',
        onComplete : function (transport, param){
            var response = false;
            if (transport && transport.responseText) {
                try {
                    response = JSON.parse(transport.responseText);
                } catch (e) {
                    console.warn('An error occured while parsing response');
                }
            }
            if (couponCodesGrid) {
                couponCodesGrid.reload();
            }
            if (response && response.messages) {
                if ($$('#'+idPrefix + 'information_fieldset .messages')) {
                    $$('#'+idPrefix + 'information_fieldset .messages')[0].update(response.messages);
                } else if ($('messages')) {
                    $('messages').update(response.messages);
                }
            }
            if (response && response.error) {
                alert({
                    content: response.error
                });
            }
        }
    });
}

Ajax.Responders.register({
    onComplete: function() {
        if ($('promo_catalog_edit_tabs_coupons_section_content')
            && $('promo_catalog_edit_tabs_coupons_section_content').visible()
            && Ajax.activeRequestCount == 0
        ) {
            handleCouponsTabContentActivity();
        }
    }
});

window.generateCouponCodes = generateCouponCodes;
window.refreshCouponCodesGrid = refreshCouponCodesGrid;
window.handleCouponTypeChange = handleCouponTypeChange;
window.handleCouponsTabContentActivity = handleCouponsTabContentActivity;
window.disableEnableCouponsTabContent = disableEnableCouponsTabContent;

registry.get('formDependenceController', function() {
    handleCouponsTabContentActivity();
    handleCouponTypeChange();
});

});
</script>
